package tool

import (
	"crypto/rand"
	"errors"
	"fmt"
	"lsgfish/server/internal/model"
	"math/big"

	"github.com/google/uuid"
)

// 生成验证码
func GenerateVerificationCode(codeLength int) (string, error) {
	if codeLength < 6 {
		codeLength = 6
	}
	max := new(big.Int).Exp(big.NewInt(10), big.NewInt(int64(codeLength)), nil)
	n, err := rand.Int(rand.Reader, max)
	if err != nil {
		return "", err
	}

	return fmt.Sprintf("%0*d", codeLength, n), nil
}

// 生成token
func GenerateToken(user model.User) (string, error) {
	token := uuid.New().String()
	if token == "" {
		return "", errors.New("生成token失败")
	}
	return token, nil
}

// 生成邀请码
func GenerateInviteCode() (string, error) {
	// 获取一个长度为10的，包含大小字母，0-9的随机字符串功能方法
	code, err := GenerateRandomCode(10)
	if err != nil {
		return "", err
	}
	return code, nil
}

// 生成随机码
func GenerateRandomCode(length int) (string, error) {
	if length < 1 {
		return "", errors.New("生成的随机码长度必须大于0")
	}
	const letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
	b := make([]byte, length)
	for i := range b {
		r, err := rand.Int(rand.Reader, big.NewInt(int64(len(letters))))
		if err != nil {
			return "", err
		}
		b[i] = letters[r.Int64() : r.Int64()+1][0]
	}
	return string(b), nil
}
